package com.ruoyi.web.controller.manage;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.implementation.bytecode.Throw;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wwy
 * @Date: 2020/12/30 16:59
 */
@Api("移动端文件上传")
@RestController
@RequestMapping("/api")
public class AppFileUploadController {
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 基础目录
     */
    @Value("${app.basePath}")
    private String basePath;

    private final static String VIDEO_TYPE = "video/mp4";

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 图片上传
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/fileUpload")
    public AjaxResult fileUpload(@RequestParam("file") MultipartFile file){
        try {
            String contentType = file.getContentType();
            System.out.println("文件类型"+contentType);
            String path = basePath;
            String fileName = FileUploadUtils.upload(path,file, MimeTypeUtils.IMAGE_VIDEO_EXTENSION);
            String webPath = "/img"+fileName;
            Map<String,Object> returnMap = new HashMap<>();
            returnMap.put("webPath",webPath);
            if(contentType.equals(VIDEO_TYPE)){
                //上传文件为video,进行截取图片
                File file1 = new File(basePath+fileName.replace("/profile/",""));
                String format = simpleDateFormat.format(new Date());
                File filePath = new File(basePath+"/videoImage/"+format);
                if(!filePath.exists()){
                    filePath.mkdirs();
                }
                String imageName = UUID.randomUUID().toString()+".jpg";
                File file2 = new File(filePath,imageName);
                File file3 = fetchFrame(file1, file2);
                String videoImageWebPath = "/img/profile/videoImage/"+format+"/"+imageName;
                returnMap.put("videoImageWebPath",videoImageWebPath);
            }
            return AjaxResult.success(returnMap);
        } catch (IOException | InvalidExtensionException e) {
            throw new CustomException("系统内部错误", HttpStatus.ERROR);
        } catch (Exception e) {
            throw new CustomException("系统内部错误", HttpStatus.ERROR);
        }

    }

    public static File fetchFrame(File file, File file4)
            throws Exception {
        long start = System.currentTimeMillis();
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
        ff.start();
        int lenght = ff.getLengthInFrames();
        int i = 0;
        Frame f = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            f = ff.grabFrame();
            if ((i > 5) && (f.image != null)) {
                break;
            }
            i++;
        }
        int owidth = f.imageWidth ;
        int oheight = f.imageHeight ;
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        Java2DFrameConverter converter =new Java2DFrameConverter();
        BufferedImage fecthedImage =converter.getBufferedImage(f);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                0, 0, null);
        //ff.flush();
        ImageIO.write(bi, "jpg", file4);
        ff.stop();
        return file4;
    }

    /**
     * 认证图片上传
     * @param file
     * @return
     */
    @ApiOperation("认证文件上传")
    @PostMapping("/authenticationFileUpload")
    public AjaxResult authenticationFileUpload(@RequestParam("file") MultipartFile file){
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            throw new CustomException("系统内部错误", HttpStatus.ERROR);
        }

    }


}
